package rabbit.flt.test.webflux;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import rabbit.flt.common.exception.FltException;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.util.concurrent.locks.LockSupport;

@RestController
@RequestMapping("/mvc")
public class BootController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @GetMapping(path = {"/helloWorld", "/hello"})
    public Mono<String> hello() {
        return Mono.just("abc");
    }

    @GetMapping("/hello1")
    public Mono<String> hello1() {
        return Mono.just("abc");
    }

    @GetMapping("/error")
    public void error() {
        throw new FltException("error");
    }

    /**
     * 未处理的异常
     */
    @GetMapping("/unHandledError")
    public String unHandledError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        // 模拟未处理的异常输出
        return "{\"timestamp\":\"2024-10-18T02:22:44.429+00:00\",\"path\":\"/mvc/unHandledError\",\"status\":500,\"error\":\"Internal Server Error\",\"requestId\":\"0868db36-1010\"}";
    }

    /**
     * 模拟休眠
     *
     * @param seconds
     */
    @GetMapping("/sleep/{seconds}")
    public Mono<Void> sleep(@PathVariable("seconds") int seconds) {
        logger.info("call sleep");
        return Mono.just(1).publishOn(Schedulers.newSingle("sleep")).flatMap(v -> {
            logger.info("server is sleep: {}", seconds);
            LockSupport.parkNanos(seconds * 1000000000L);
            logger.info("server is waked up");
            return Mono.empty();
        });
    }
}
